<?php

namespace App\Http\Controllers;

use Spatie\QueryBuilder\QueryBuilder;
use Spatie\QueryBuilder\AllowedFilter;
use Spatie\QueryBuilder\AllowedInclude;
use App\Http\Controllers\Controller;

class BaseController extends Controller
{
    protected $module;
    protected $modelclass;

    public function __construct()
    {
        //$this->model = new 
    }    
    /**
     * Display a listing of the resource.
     * 查询
     * ?filter[cate_id]=10&title=imya
     * ?field['posts']=id,user_id,cate_id,title&field['user']=id,name&field[cate]=id,title
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $this->model = new Cate();

        //参数可以在取后修改
        $param = $this->model->getQueryAll();

        //也可是一个查询 $query = $model->where('status',1);
        //$param['list_fields']排除了list_hidden字段
        //不能直接使用$query = $this->model,可使用$query = Post::class;    
        $query = $this->model->select($param['list_fields']);

             //可更改request自定义默认参数
        //如强设参数 request()->offsetSet('filter', ['cate_id'=>10]);

        $data = $this->queryBuilder($query,$param);
        
        return json_ok($data->toArray());
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Modules\Blog\Http\Requests\BlogCreateRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(BlogCreateRequest $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $data = Post::with(Post::showWith())->findOrFail($id);
        $result['data'] = (new PostResource($data))->resolve();
        $result['module'] = get_module($this->module);
        dd($result);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Modules\Blog\Http\Requests\BlogUpdateRequest  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(BlogUpdateRequest $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    protected function queryBuilder($query,array $param=[])
    {       
//sql_start();
        $request=request();
        if(!$request->has('include') && !empty($param['list_with'])){
            //list_with必须在includes范围内,否则会出错
            $request->offsetSet('include', str2arr($param['list_with']));
        }
            //dump("defaultIncludes('".arr2str($param['includes'])."')");
        $data = QueryBuilder::for($query);
        
        if($param['sort']){
            $data = $data->defaultSort($param['sort']);
            //dump("defaultSort('".$param['sort'].")");
        }                 
        if($param['sorts']){
            $data = $data->allowedSorts($param['sorts']);
            //dump("allowedSorts('".arr2str($param['sorts'])."')");
        }
        if($param['filters']){
            $data = $data->allowedFilters($param['filters']);
            //dump("allowedFilters('........')");
        }
        if($param['fields']){
            $data = $data->allowedFields($param['fields']);
            //dump($request->get('fields'));
        }
        if($param['appends']){     
            $data = $data->allowedAppends($param['appends']);
            //dump("defaultAppends('".arr2str($param['appends'])."')");
        }
        if($param['includes']){
            $data = $data->allowedIncludes($param['includes']);
        }
        
		$limit    = (int)$request->get('limit',0);
        $per_page = (int)$request->get('per_page',0);

        if( $limit > 0 ){
            $data = $data->simplePaginate($limit);
        }elseif($per_page > 0){
            $data = $data->paginate($per_page);
        }else{
            $data = $data->paginate();   
        }        
        $data = $data->appends($request->query());
        return $data;

//sql_end();           
    }  

    protected function help(array $param=[])
    {
		$query	= [
			'include' => config('query-builder.parameters.include'),
			'filter'  => config('query-builder.parameters.filter'),
			'sort'    => config('query-builder.parameters.sort'),
			'fields'  => config('query-builder.parameters.fields'),
			'append'  => config('query-builder.parameters.append')
            ];

        
        foreach ($param['filters'] as $key => $value) {
            if($value instanceof AllowedFilter){
                $param['filters'][$value->getName()] = $value->getInternalName(); 
            }else{
                $param['filters'][$value]='like';
            }
            unset($param['filters'][$key]);
        }
        $simple = 'limit';
        return json_ok(compact('query','param','simple'));
    }    
}
